package com.itheima.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.common.R;
import com.itheima.pojo.Employee;
import com.itheima.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/employee")
public class EmployeeController {

    @Autowired
    private EmployeeService employeeService;

    //登录
    @PostMapping("/login")
    public R login(@RequestBody Employee employee, HttpSession session) {
        //1.判断用户输入的数据,是否为空
        if (employee == null
                || StringUtils.isEmpty(employee.getUsername())
                || StringUtils.isEmpty(employee.getPassword())) {
            return R.error("账户或密码不能为空");
        }
        //2.封装条件，与数据库比对信息
        LambdaQueryWrapper<Employee> qw = new LambdaQueryWrapper<>();
        qw.eq(Employee::getUsername, employee.getUsername());
        //2.1将条件放入方法中
        Employee one = employeeService.getOne(qw);
        //2.2对比
        if (one == null) {
            return R.error("账户不存在");
        }
        //3.获取密文密码
        String password = one.getPassword();
        //3.1将用户输入的密码加密
        String s = DigestUtils.md5DigestAsHex(employee.getPassword().getBytes());
        //4.匹配
        if (password.equals(s)) {
            session.setAttribute("employee", one.getId());
            return R.success(one);
        }
        return R.error("用户名或密码错误");
    }

    //登出
    @PostMapping("/logout")
    public R<String> logout(HttpSession session) {
        //退出登录，清空session数据
        session.removeAttribute("employee");
        return R.success("退出成功");
    }

    //添加
    @PostMapping
    public R<String> save(@RequestBody Employee employee, HttpServletRequest request){
        //1.处理，补全参数（浏览器里输入，表里没有的数据）
        employee.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));
        //2.添加修改的时间
        employeeService.save(employee);
        return R.success("添加成功");
    }

    //分页查询
    @GetMapping("/page")
    public R page( int page,int pageSize,String name){
        //分页构造器
        Page<Employee> pg = new Page(page,pageSize);
        //条件构造器
        LambdaQueryWrapper<Employee> qw = new LambdaQueryWrapper<>();
        qw.like(StringUtils.isNotEmpty(name),Employee::getName,name);//1.判断那么是否为空，2.对比数据库和用户输入的那name
        qw.orderByDesc(Employee::getUpdateTime);//排序
        employeeService.page(pg,qw);
        //获取分页结果
        List<Employee> records = pg.getRecords();
        long total = pg.getTotal();
        Map<String, Object> map = new HashMap<>();
        map.put("records",records);
        map.put("total",(int)total);
        return R.success(map);
    }

    //(查询员工信息)
    @GetMapping("/{id}")
    public R<Employee> getById(@PathVariable Long id){
        //回显数据
        Employee byId = employeeService.getById(id);
        if (byId != null){
            return R.success(byId);
        }
        return R.error("查无信息");
    }

    //修改，启用·禁用员工
    @PutMapping
    public R<String> update(@RequestBody Employee employee,HttpServletRequest request){
        //1.修改当前时间
        employee.setUpdateTime(LocalDateTime.now());
        //2.当前修改的用户是谁
        //获取用户id
        Long o = (Long) request.getSession().getAttribute("employee");
        employee.setUpdateUser(o);
        employeeService.updateById(employee);
        return R.success("开启启用");
    }

}

